<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <!--      加上clearable这个属性可以快速清除也就是那个叉叉顺便刷新一下 v-model="data.name" 将输入的文字显示到输入框内-->
      <el-input clearable @clear="load" style="width: 240px;margin-right: 5px;" v-model="data.title" placeholder="请输入标题查询" :prefix-icon="Search"></el-input>

      <el-button type="primary" @click="load">查 询</el-button>
      <el-button @click="reset">重 置</el-button>
    </div>


    <div class="card" style="margin-bottom: 5px" v-if="data.user.role === 'USER'">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
    </div>


    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" style="width: 100%" :header-cell-style="{fontWeight: 'bold',color: '#333',backgroundColor: '#c902f6'}">

        <el-table-column  label="攻略主图" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.img" :preview-src-list="[scope.row.img]"
                      :src="scope.row.img" :preview-teleported="true"
                      style="width: 50px; height: 40px;border-radius: 5px;display: block;"
                      lazy
                      @load="() => console.log('图片加载完成:', scope.row.img)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="攻略标题"/>
        <el-table-column prop="categoryTitle" label="攻略分类"/>
        <el-table-column prop="username" label="发布用户"/>
        <el-table-column prop="content" label="攻略内容">
          <template v-slot="scope">
            <el-button type="primary" @click="viewContent(scope.row.content)">点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="发布时间" />
        <el-table-column label="操作" width="100" v-if="data.user.role === 'ADMIN'">
          <template #default="scope">
            <el-button type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-size="data.pageSize"
          layout="total,sizes, prev, pager, next,jumper"
          :page-sizes="[5,10,20]"
          :total="data.total"
          @current-change="load"
          @size-change="load"

      />
    </div>





    <el-dialog v-model="data.formVisible" title="攻略信息" width="60%" destroy-on-close>
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="80px" style="padding: 20px 30px 10px 0">

        <el-form-item prop="img" label="攻略主图" >
          <el-upload
              action="http://localhost:9999/files/upload"
              :headers="{ token: data.user.token }"
              :on-success="handleFileSuccess"
              list-type="picture"
              :before-upload="beforeFileUpload"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="title" label="攻略标题">
          <el-input v-model="data.form.title" autocomplete="off" placeholder="请输入攻略标题"/>
        </el-form-item>

        <el-form-item prop="title" label="攻略分类">
          <el-select
              v-model="data.form.categoryId"
              placeholder="请选择分类"
              size="large"
              style="width: 100%"
          >
            <el-option
                v-for="item in data.categoryData"
                :key="item.categoryTitle"
                :label="item.title"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="content" label="攻略详情">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.content"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm">Cancel</el-button>
          <el-button type="primary" @click="save()">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog v-model="data.viewVisible" title="攻略信息" width="60%" destroy-on-close>
      <div v-html="data.content" style="padding: 0 28px"></div>
    </el-dialog>
  </div>
</template>
<script setup>

import {Search} from "@element-plus/icons-vue";
import '@wangeditor/editor/dist/css/style.css' //引入css
import {onBeforeUnmount,reactive,ref,shallowRef} from "vue";
import { Editor,Toolbar } from '@wangeditor/editor-for-vue'
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";


const formRef = ref()
const data = reactive({
  user: JSON.parse(localStorage.getItem('code2025_user') || "{}"),
  title: null,
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  form: {},
  formVisible: false,
  content: null,
  viewVisible: false,
  categoryData: [],
  rules: {
    title: [
      {required: true,message: '请填写攻略标题',trigger: 'blur'}
    ],
    content: [
      {required: true,message: '请填写攻略内容',trigger: 'blur'}
    ],

  }
})
const toolbarConfig = {} //我加了这个 才能把图片放进去 :defaultConfig="editorConfig" :defaultConfig="toolbarConfig"
/* wangEditors 初始化开始 */
const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: {
    token: data.user.token,
  },
  server: "http://localhost:9999/files/wang/upload", // 服务器端图片上传接口
  fieldName: 'file' // 服务端图片上传接口参数
}
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy();
    editorRef.value = undefined;  // 避免残留引用
  }
});
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor;
  // 如果表单有旧内容，初始化编辑器内容
  if (data.form.content) {
    editorRef.value.setHtml(data.form.content);
  }
};
/* wangEditor5 初始化结束 */

const viewContent = (content) => {
  data.content = content
  data.viewVisible = true
}

const load = () => {
  request.get('/introduction/selectPage',{
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.title
    }
  }).then(res=>{
    if(res.code === '200'){
      data.tableData = res.data?.list
      data.total = res.data?.total
    }else{
      ElMessage.error(res.msg)
    }
  })
}
load()

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}

// 在对话框关闭时重置表单（包括图片）
const resetForm = () => {
  data.form = {};  // 清空表单数据
  // 确保编辑器存在后再销毁
  if (editorRef.value) {
    editorRef.value.destroy();
    editorRef.value = undefined;  // 重置引用
  }
  data.formVisible = false;
};
const add = () => {
  request.post('/introduction/add',data.form).then(res => {
    if(res.code==='200'){
      ElMessage.success("新增成功")
      data.formVisible = false
      load()
    }else{
      ElMessage.error(res.msg)
    }
  })
}

const save = () => {
  formRef.value.validate(valid => {
    if(valid) {
      data.form.id?update():add()
    }else{
      ElMessage.error(res.msg)
    }
  })
}

const update = () => {
  request.put('/introduction/update',data.form).then(res => {
    if(res.code === '200'){
      ElMessage.success('更新成功')
      data.formVisible = false
      load()
    }else{
      ElMessage.error(res.msg)
    }
  })
}


const del = (id)=>{
  ElMessageBox.confirm('删除后无法恢复,您确认删除吗?','删除确认',{ type:"warning" }).then(res => {
    request.delete('/introduction/delete/'+id).then(res=>{
      if(res.code === '200'){
        ElMessage.success('删除成功')
        load()
      }else{
        ElMessage.error(res.msg);
      }
    })
  }).catch(err=>{

  })
}

const reset = () =>{
  data.title = null;
  load()
}

const handleFileSuccess = (res) => {
  data.form.img = res.data
}

// 文件上传前的校验方法
const beforeFileUpload = (file) => {
  const maxSize = 10 * 1024 * 1024; // 2MB 限制
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过 10MB!');
    return false; // 阻止上传
  }
  return true; // 允许上传
};

const loadCategory = () => {
  request.get('/category/selectAll').then(res=>{
    if(res.code === '200'){
      data.categoryData = res.data
    }else{
      ElMessage.error(res.msg)
    }
  })
}
loadCategory()







</script>